package com.tao.util.pack.send.util;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import com.tao.domain.User;
import com.tao.util.BaseRequest;
import com.tao.util.pack.Msg;


public class SendFileUtils {
//	static String cookie = "pgv_pvi=757308416; webwxuvid=4641d6eb4ec9a56b6a127279bd4f22de066d87a0bd5ecbb6fdec5c1c948d93b8bb9f3fb391f1fa0541ba6dc733caa171; MM_WX_NOTIFY_STATE=1; MM_WX_SOUND_STATE=1; pgv_si=s4948172800; wxuin=2190998410; wxsid=GpvIGeNpNIDxRFuL; wxloadtime=1477818220; mm_lang=zh_CN; webwx_data_ticket=gSdvkCl4jz0fLtcz04rIASSR";
//static String filePath = "C:/Users/he/Desktop/13软件工程2班.xls";
//static String uIn = "2190998410";
//static String sId = "GpvIGeNpNIDxRFuL";
//static String sKey = "crypt_fd1a2568_02d9590e060fdc24d60c98eb74470196";
//static String pass_ticket="MK0ZwXyM%252B70ykCaWqwBGNpriZ06R5eLO4JsRpheiDzjlPSn7cjwgyDwy5preeTGA";
//static String fileName = "13软件工程2班.xls";
//static String   fromUserName="0f138454fd5b10e6203842156fe4d5dbf0b0592279b4af79e5b6a331f0d550da";
//static String  toUserName="422865dfcebe4ce0a81808fa9932aec72d8581f9f960e95bc91cda1a980e8711";
public static String upload(String filePath,String uIn,String sId,String sKey,int fileType) {
//        // set https proxy
//        System.setProperty("https.proxyHost", "127.0.0.1");
//        System.setProperty("https.proxyPort", "8888");

        String response = null;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        HttpsURLConnection conn = null;
        try {
            File file = new File(filePath);
            if (!file.exists() || !file.isFile()) {
                throw new IOException("文件不存在");
            }

            //请求头参数
            String boundary = "----WebKitFormBoundary6oVvR66QUmo1TkXD"; //区分每个参数之间
            String freFix = "--";
            String newLine = "\r\n";

            URL urlObj = new URL("https://file2.wx.qq.com/cgi-bin/mmwebwx-bin/webwxuploadmedia?f=json");
            conn = (HttpsURLConnection) urlObj.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);  
            conn.setDoInput(true);  
            conn.setUseCaches(false);
            conn.setRequestProperty("Accept", "*/*");
            conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
            conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
            conn.setRequestProperty("Cache-Control", "no-cache");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Content-Length", Long.toString(file.length()));
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary);
            conn.setRequestProperty("Host", "file2.wx.qq.com");
            conn.setRequestProperty("Origin", "https://wx2.qq.com");
            conn.setRequestProperty("Pragma", "no-cache");
            conn.setRequestProperty("Referer", "https://wx2.qq.com/");
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0");

            // 请求主体
            StringBuffer sb = new StringBuffer();

            sb.append(freFix+boundary).append(newLine); //这里注意多了个freFix，来区分去请求头中的参数
            sb.append("Content-Disposition: form-data; name=\"name\"");
            sb.append(newLine).append(newLine);
            sb.append(file.getName()).append(newLine);

            sb.append(freFix+boundary).append(newLine);
            sb.append("Content-Disposition: form-data; name=\"lastModifiedDate\"");
            sb.append(newLine).append(newLine);
            sb.append("Mon Oct 17 2016 20:28:35 GMT+0800 (中国标准时间)").append(newLine);

            sb.append(freFix+boundary).append(newLine);
            sb.append("Content-Disposition: form-data; name=\"size\"");
            sb.append(newLine).append(newLine);
            sb.append(file.length()).append(newLine);

            sb.append(freFix+boundary).append(newLine);
            sb.append("Content-Disposition: form-data; name=\"mediatype\"");
            sb.append(newLine).append(newLine);
            sb.append("doc").append(newLine);

            sb.append(freFix+boundary).append(newLine);
            sb.append("Content-Disposition: form-data; name=\"uploadmediarequest\"");
            sb.append(newLine).append(newLine);
            sb.append("{\"BaseRequest\":{\"Uin\":"+uIn+",\"Sid\":\""+sId+"\",\"Skey\":\"@"+sKey+"\",\"DeviceID\":\"e823469202135602\"},\"ClientMediaId\": "+System.currentTimeMillis()+",\"TotalLen\":"+file.length()+",\"StartPos\":0,\"DataLen\":"+file.length()+",\"MediaType\":4}").append(newLine);

            sb.append(freFix+boundary).append(newLine);
            sb.append("Content-Disposition: form-data; name=\"webwx_data_ticket\"");
            sb.append(newLine).append(newLine);
            sb.append("gSdvkCl4jz0fLtcz04rIASSR").append(newLine);


            sb.append(freFix+boundary).append(newLine);
            sb.append("Content-Disposition: form-data; name=\"filename\"; filename=\""+file.getName()+"\"");
            sb.append(newLine);
            sb.append("Content-Type: application/vnd.ms-excel");
            sb.append(newLine).append(newLine);

            OutputStream outputStream = new DataOutputStream(conn.getOutputStream());
            outputStream.write(sb.toString().getBytes("utf-8"));//写入请求参数

            DataInputStream dis = new DataInputStream(new FileInputStream(file));  
            int bytes = 0;  
            byte[] bufferOut = new byte[1024];  
            while ((bytes = dis.read(bufferOut)) != -1) {  
                 outputStream.write(bufferOut,0,bytes);//写入图片
            }
            outputStream.write(newLine.getBytes());
            outputStream.write((freFix+boundary+freFix+newLine).getBytes("utf-8"));//标识请求数据写入结束

            dis.close();  
            outputStream.close();

            //读取响应信息
            inputStream = conn.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
            bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            response = buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(conn!=null){
                conn.disconnect();
            }
            try {
                bufferedReader.close();
                inputStreamReader.close();
                inputStream.close();
            } catch (IOException execption) {

            }
        }
        return response;
    }

    public static String send(String filePath,String fileName,User user,BaseRequest bRequest,Msg msg) throws JSONException{
      
        int mediaType = 4;
        String result = upload(filePath,user.getUin(),user.getSid(),user.getSkey(),mediaType);//执行图片上传，返回流媒体id。PS：微信网页版中的发送文件/图片/等分为两步1.上传到服务器拿到返回的mediaId,2.发送通知消息

        JSONObject json = new JSONObject(result);
        String mediaId = json.get("MediaId").toString();
        System.out.println(json.get("MediaId"));

        //发送图片
        Long currentTimeMillis = System.currentTimeMillis();

        String jsonParamsByFile = "{\"BaseRequest\":{\"Uin\":"+user.getUin()+",\"Sid\":\""+user.getSid()+"\",\"Skey\":\""+user.getSkey()+"\",\"DeviceID\":\"e640359774620125\"},\"Msg\":{\"Type\":6,\"Content\":\"<appmsg appid=\'wxeb7ec651dd0aefa9\' sdkver=\'\'><title>"+fileName+"</title><des></des><action></action><type>6</type><content></content><url></url><lowurl></lowurl><appattach><totallen>9879</totallen><attachid>"+mediaId+"</attachid><fileext>xlsx</fileext></appattach><extinfo></extinfo></appmsg>\",\"FromUserName\":\""+user.getUserName()+"\",\"ToUserName\":\""+msg.getToUserName()+"\",\"LocalID\":\""+currentTimeMillis+"\",\"ClientMsgId\":\""+currentTimeMillis+"\"}}";

        //cookie  ="";
        System.out.println(jsonParamsByFile);
        String url = "https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxsendappmsg?fun=async&f=json&pass_ticket="+user.getPass_ticket();  
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        post.addHeader(new BasicHeader("cookie", user.getCookie()));//发送文件必须设置,cookie

        try {
            StringEntity s = new StringEntity(jsonParamsByFile,"UTF-8");
            post.setEntity(s);
            HttpResponse res = client.execute(post);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                HttpEntity entity = res.getEntity();
                String resultstring = EntityUtils.toString(entity, "utf-8");
                System.out.println(resultstring);
                return resultstring;
            }
        } catch (Exception e) {
        	 System.out.println("网络超时");
        } 
        return null;
    }
    public static void main(String[] args) {
//    String s = 	upload("C:/Users/he/Desktop/13软件工程2班.xls", "2190998410", "GpvIGeNpNIDxRFuL", "crypt_fd1a2568_02d9590e060fdc24d60c98eb74470196", 1);
//    	System.out.println(s);
//    		try {
//		send(filePath, cookie,uIn, sId, sKey, fileName, fromUserName, toUserName);
//	} catch (JSONException e) {
//		// TODO Auto-generated catch block
//		e.printStackTrace();
//	}
    	
    }
}